import tkinter as tk
from tkinter import filedialog, messagebox
import os
from zipfile import ZipFile, ZIP_DEFLATED


def choose_files_and_zip():
    files = filedialog.askopenfilenames(title="选择要压缩的文件")
    if not files:
        return

    save_path = filedialog.asksaveasfilename(
        title="保存为ZIP压缩文件",
        defaultextension=".zip",
        filetypes=[("ZIP 文件", "*.zip")],
        initialfile="压缩文件.zip",
    )
    if not save_path:
        return

    try:
        # 根据选中文件的共同父目录，尽量保留相对路径，避免同名文件冲突
        common_root = None
        try:
            common_root = os.path.commonpath(files)
            if not os.path.isdir(common_root):
                common_root = os.path.dirname(common_root)
        except Exception:
            common_root = None

        with ZipFile(save_path, "w", compression=ZIP_DEFLATED) as zf:
            for f in files:
                try:
                    if common_root and os.path.commonpath([common_root, f]) == common_root:
                        arcname = os.path.relpath(f, start=common_root)
                    else:
                        arcname = os.path.basename(f)
                    zf.write(f, arcname)
                except Exception as fe:
                    print(f"跳过文件 {f}: {fe}")

        messagebox.showinfo("完成", f"已创建ZIP：\n{save_path}\n包含 {len(files)} 个文件。")
    except Exception as e:
        messagebox.showerror("错误", f"压缩失败：{e}")


if __name__ == "__main__":
    root = tk.Tk()
    root.withdraw()
    choose_files_and_zip()
    root.destroy()